package com.alibaba.citrus.cr.b2b.trade.order.repository.impl;

import com.alibaba.citrus.cr.b2b.trade.order.repository.OrderLineWriteRepository;
import com.alibaba.citrus.cr.b2b.trade.order.repository.request.UpdateFeaturesReq;
import com.alibaba.citrus.cr.common.annotation.EpochTransactional;
import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.common.enums.ordercenter.SalesOrderCloseEnum;
import com.alibaba.citrus.cr.common.exception.RepositoryException;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.model.dto.GetScItemUnitInfoRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crb2btradecenter.domain.order.dto.UpdateFeaturesResponse;
import com.epoch.app.crb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.*;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.crb2btradecenter.enums.OrderStatus;
import com.epoch.app.crb2btradecenter.model.dto.SelectCombox;
import com.epoch.app.crb2btradecenter.model.dto.UpdateFeaturesRequest;
import com.epoch.app.crb2btradecenter.sdo.OrderLineSDO;
import com.epoch.app.crb2btradecenter.sdo.ScItemSDO;
import com.epoch.app.crforecastsales.api.forecastorderwrite.service.ForecastOrderWriteService;
import com.epoch.app.crforecastsales.model.dto.SaleUnit;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class OrderLineWriteRepositoryImpl implements OrderLineWriteRepository {

    private static final Log log = Log.getLogger(OrderLineWriteRepositoryImpl.class);

    @Autowired
    private ForecastOrderWriteService forecastOrderWriteService;

    @Autowired
    private OrderLineService orderLineService;
    @Autowired
    private OrderService orderService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private CrPlatformEnhanceService crPlatformEnhanceService;

    @Override
    public String batchCreateOrderLine(OrderLineSDO orderLineSDO) {
        OrderLine orderLine = createOrderLineConverter(orderLineSDO);
        CreateOrderLineResponse orderLine1 = orderLineService.createOrderLine(orderLine);
        if (orderLine1.getLastInsertId() == null) {
            log.error("OrderLineWriteRepositoryImpl$batchCreateOrderLine_fail");
        }
        return orderLine1.getLastInsertId();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Boolean modifyOrderLine(OrderLineSDO orderLineSDO) {
//        String unitName = getScItemUnitName(orderLineSDO);
        OrderLine orderLine = createOrderLineConverter(orderLineSDO);
//        orderLine.setSaleUnitName(unitName);
        LoadOrderLineRequest loadOrderLineRequest = new LoadOrderLineRequest();
        OrderLine orderLine1 = new OrderLine();
        if (null != orderLine.getId()) {
            loadOrderLineRequest.setId(String.valueOf(orderLine.getId()));
            orderLine1 = orderLineService.loadOrderLine(loadOrderLineRequest);
        }
        orderLine.setSyncVersion(orderLine1.getSyncVersion());
        log.info("OrderLineWriteRepositoryImpl#modifyOrderLine orderLine:{}", JSON.toJSONString(orderLine));
        UpdateOrderLineResponse updateOrderLineResponse = orderLineService.updateOrderLine(orderLine);
        if (updateOrderLineResponse.getCount() != 1) {
            log.error("OrderLineWriteRepositoryImpl$modifyOrderLine_fail");
        }
        return true;
    }

    @Override
    public Boolean batchUpdateOrderLine(String orderId, Integer status) {
        BatchUpdateStatusRequest request = new BatchUpdateStatusRequest();
        request.setMainOrderId(orderId);
        request.setStatus(status);
        orderLineService.batchUpdateStatus(request);
        return true;
    }

    @Override
    @RepositoryInvoker
    public String remove(OrderLineSDO orderLineSDO) {
        DeleteOrderLineRequest deleteOrderLineRequest = new DeleteOrderLineRequest();
        deleteOrderLineRequest.setId(orderLineSDO.getId());
        DeleteOrderLineResponse deleteOrderLineResponse = orderLineService.deleteOrderLine(deleteOrderLineRequest);
        if (deleteOrderLineResponse.getCount() != 1) {
            throw new RuntimeException("delete OrderLineSDO effect rows not 1!");
        }
        return orderLineSDO.getId();
    }

    @Override
    public Boolean modify(OrderLineSDO orderLineSDO) {
        LoadOrderLineRequest loadOrderLineRequest = new LoadOrderLineRequest();
        loadOrderLineRequest.setId(orderLineSDO.getId());
        ScItemSDO scItemSDO = orderLineSDO.getScItemSDO();
        OrderLine orderLine = orderLineService.loadOrderLine(loadOrderLineRequest);
        if (!org.springframework.util.StringUtils.isEmpty(orderLineSDO.getId())) {
            orderLine.setId(Long.parseLong(orderLineSDO.getId()));
        }
        orderLine.setRefuseReasonCode(orderLineSDO.getRefuseReasonCode());
        orderLine.setRemark(orderLineSDO.getRemark());
        orderLine.setInventoryUnitCode(scItemSDO.getInventoryUnitCode());
        orderLine.setInventoryUnit(scItemSDO.getInventoryUnitName());
        if (null != orderLineSDO.getScItemSDO()) {
            orderLine.setQuantity(scItemSDO.getQuantity());
            orderLine.setUnitPrice(scItemSDO.getUnitPrice() == null ? null:scItemSDO.getUnitPrice().toString());
        }
        orderLine.setSaleUnit(scItemSDO.getSaleUnit());
        orderLine.setSaleUnitName(scItemSDO.getSaleUnitName());
        if (StringUtils.isNotBlank(orderLineSDO.getCumulativeDeliveryQuantity())){
            orderLine.setCumulativeDeliveryQuantity(orderLineSDO.getCumulativeDeliveryQuantity());
        }
        UpdateOrderLineResponse updateOrderLineResponse = orderLineService.updateOrderLine(orderLine);
        if (updateOrderLineResponse.getCount() != 1) {
            throw new RuntimeException("modify OrderLineSDO effect rows not 1!");
        }
        return true;
    }

    @Override
    public String save(OrderLineSDO orderLineSDO) {
        OrderLine orderLine = createOrderLineConverter(orderLineSDO);
        log.info("OrderLineWriteRepositoryImpl save orderLine={}",JSON.toJSONString(orderLine));
        CreateOrderLineResponse orderLine1 = orderLineService.createOrderLine(orderLine);
        log.info("OrderLineWriteRepositoryImpl save orderLine1={}",JSON.toJSONString(orderLine1));
        if (orderLine1.getLastInsertId() == null) {
            log.error("OrderLineWriteRepositoryImpl$save_fail");
        }
        return orderLine1.getLastInsertId();
    }

    private String getScItemUnitName(OrderLineSDO orderLineSDO) {
        String saleUnitName = null;
        if (null != orderLineSDO.getScItemSDO() && orderLineSDO.getScItemSDO().getScItemId() != null) {
            GetScItemUnitInfoRequest query = new GetScItemUnitInfoRequest();
            query.setScItemId(orderLineSDO.getScItemSDO().getScItemId());
            Map map = (Map) baseDataService.getScItemUnitInfo(query);
            List<SelectCombox> selectComboxes = new ArrayList<>();
            if (map.get("result") != null){
                String js = JSON.toJSONString(map.get("result"));
                List<SaleUnit> saleUnits = JSONArray.parseArray(js,SaleUnit.class);
                if (CollectionUtils.isNotEmpty(saleUnits)){
                    selectComboxes = saleUnits.stream().map(saleUnit -> {
                        SelectCombox selectCombox = new SelectCombox();
                        selectCombox.setLabel(saleUnit.getUnitName()==null?saleUnit.getFeatures():saleUnit.getUnitName());
                        selectCombox.setValue(saleUnit.getUnitCode());
                        selectCombox.setExt(saleUnit.getRelationNum().toString());
                        return selectCombox;
                    }).collect(Collectors.toList());
                }
                Map<String,SelectCombox> stringSelectComboxMap = selectComboxes.stream().collect(Collectors.toMap(SelectCombox::getValue,o->o,(k1,k2)->k2));
                saleUnitName = stringSelectComboxMap.get(orderLineSDO.getScItemSDO().getSaleUnit()).getLabel();
            }
        }
        return saleUnitName;
    }

    @Override
    public Boolean modifyStatus(OrderLineSDO orderLineSDO) {
        LoadOrderLineRequest loadOrderLineRequest = new LoadOrderLineRequest();
        loadOrderLineRequest.setId(orderLineSDO.getId());
        OrderLine orderLine = orderLineService.loadOrderLine(loadOrderLineRequest);
        orderLine.setStatus(orderLineSDO.getStatus());
        orderLine.setClosed(orderLineSDO.getClosed());
        orderLine.setDeliveryAmount(orderLineSDO.getDeliveryAmount());
        orderLine.setRefuseReasonCode(orderLineSDO.getRefuseReasonCode());
        orderLine.setRefuseReasonName(orderLineSDO.getRefuseReasonName());
        orderLine.setFeatures(JSON.toJSONString(orderLineSDO.getFeatures()));
        orderLine.setModifierId(orderLineSDO.getModifierId());
        orderLine.setModifierName(orderLineSDO.getModifierName());
        orderLine.setGmtModified(orderLineSDO.getGmtModified());
        orderLineService.updateOrderLine(orderLine);
        return true;
    }

    @Override
    public Boolean batchModifyStatus(List<OrderLineSDO> orderLineSDOList) {
        if(CollectionUtils.isEmpty(orderLineSDOList)){
            return false;
        }
        BatchUpdateStatusRequest batchUpdateStatusRequest = new BatchUpdateStatusRequest();
        List<String> orderLineIds = orderLineSDOList.stream().map(OrderLineSDO::getId).collect(Collectors.toList());
        batchUpdateStatusRequest.setOrderLineIds(orderLineIds);
        OrderLineSDO orderLine = orderLineSDOList.get(0);
        batchUpdateStatusRequest.setStatus(orderLine.getStatus());
        batchUpdateStatusRequest.setRefuseReasonCode(orderLine.getRefuseReasonCode());
        batchUpdateStatusRequest.setRefuseReasonName(orderLine.getRefuseReasonName());
        batchUpdateStatusRequest.setClosed(orderLine.getClosed());
        batchUpdateStatusRequest.setModifierId(orderLine.getModifierId());
        batchUpdateStatusRequest.setModifierName(orderLine.getModifierName());
        batchUpdateStatusRequest.setGmtModified(new Date());
        log.info("batchUpdateStatusRequest参数:{}",JSON.toJSONString(batchUpdateStatusRequest));
        orderLineService.batchUpdateStatus(batchUpdateStatusRequest);
        return true;
    }

    @Override
    public Boolean batchCancel(String modifierCode, String modifierName, String refuseReason, List<String> mainOrderBizIds) {
        BatchcancelRequest batchcancelRequest = new BatchcancelRequest();
        batchcancelRequest.setModifierId(modifierCode);
        batchcancelRequest.setModifierName(modifierName);
        batchcancelRequest.setStatus(OrderStatus.CANCELLED.getCode());
        // batchcancelRequest.setClosed(1);
        batchcancelRequest.setMainOrderBizIds(mainOrderBizIds);
        if (StringUtils.isBlank(refuseReason)) {
            batchcancelRequest.setRefuseReasonCode(SalesOrderCloseEnum.SALES_COMPANY_CLOSE_ITEM.getCode()); //默认取消原因是Z1，为了释放预占的库存
            batchcancelRequest.setRefuseReasonName(SalesOrderCloseEnum.SALES_COMPANY_CLOSE_ITEM.getDesc());
        } else {
            batchcancelRequest.setRefuseReasonCode(refuseReason);
            batchcancelRequest.setRefuseReasonName(SalesOrderCloseEnum.descByCode(refuseReason));
        }
        orderLineService.batchcancel(batchcancelRequest);
        return true;
    }

    /**
     * 本方法 给修改明细行 优化性能-不用先查出来再去更新用
     *  暂时是给关闭方法里修改 修改人id和名称用， 后面有别的字段要单独根据id更新 再调整本方法及纪元内容
     * @param orderLineSDO
     * @return
     */
    @Override
    public Boolean modifyModifier(OrderLineSDO orderLineSDO) {
        ModifyOrderLineRequest modifyOrderLineRequest=new ModifyOrderLineRequest();
        modifyOrderLineRequest.setId(orderLineSDO.getId());
        modifyOrderLineRequest.setModifierId(orderLineSDO.getModifierId());
        modifyOrderLineRequest.setModifierName(orderLineSDO.getModifierName());
        orderLineService.modifyOrderLine(modifyOrderLineRequest);
        return true;
    }

    @Override
    public Boolean modifyStatusForVersion(OrderLineSDO orderLineSDO) {
        LoadOrderLineRequest loadOrderLineRequest = new LoadOrderLineRequest();
        loadOrderLineRequest.setId(orderLineSDO.getId());
        OrderLine orderLine = orderLineService.loadOrderLine(loadOrderLineRequest);
        orderLine.setStatus(orderLineSDO.getStatus());
        orderLine.setClosed(orderLineSDO.getClosed());
        orderLine.setDeliveryAmount(orderLineSDO.getDeliveryAmount());
        orderLine.setRefuseReasonCode(orderLineSDO.getRefuseReasonCode());
        orderLine.setRefuseReasonName(orderLineSDO.getRefuseReasonName());
        orderLine.setFeatures(JSON.toJSONString(orderLineSDO.getFeatures()));
        orderLine.setModifierId(orderLineSDO.getModifierId());
        orderLine.setModifierName(orderLineSDO.getModifierName());
        orderLine.setGmtModified(orderLineSDO.getGmtModified());
        orderLine.setSyncVersion(orderLineSDO.getSyncVersion());
        UpdateOrderLineForVersionResponse updateOrderLineForVersionResponse = orderLineService.updateOrderLineForVersion(orderLine);
        if (Objects.isNull(updateOrderLineForVersionResponse)||Objects.isNull(updateOrderLineForVersionResponse.getCount())||updateOrderLineForVersionResponse.getCount()!=1){
            throw new RepositoryException("OTS-04-001-00-16-055");
        }
        return true;
    }

    @Override
    @RepositoryInvoker
    @EpochTransactional(appCode="cr_b2b_trade_center", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Boolean updateFeatures(UpdateFeaturesReq updateFeaturesReq) {
        if (updateFeaturesReq != null && updateFeaturesReq.getOrderId() != null) {
//            List<Map<String, String>> orderLineFeatures = updateFeaturesReq.getSubOrderFeaturesToUpdate() == null ? null : Lists.newArrayList(updateFeaturesReq.getSubOrderFeaturesToUpdate().values());
            if (MapUtils.isNotEmpty(updateFeaturesReq.getMainOrderFeaturesToUpdate())){
                Map<String, String> mainOrderFeaturesToUpdate = updateFeaturesReq.getMainOrderFeaturesToUpdate();
                UpdateFeaturesRequest request = new UpdateFeaturesRequest();
                request.setId(updateFeaturesReq.getOrderId());
                request.setFeatures(JSON.toJSONString(mainOrderFeaturesToUpdate));
                request.setSyncVersion(updateFeaturesReq.getOrderSyncVersionToCheck());
                UpdateFeaturesResponse affectedRows = this.orderService.updateFeatures(request);
                if (affectedRows.getCount() <= 0L) {
                    log.error("OrderLineWriteRepositoryImpl#updateFeatures_fail");
                    throw new RepositoryException("OTS-05-001-10-16-032");
                }
            }

            if (updateFeaturesReq.getSubOrderFeaturesToUpdate() != null) {
                updateFeaturesReq.getSubOrderFeaturesToUpdate().forEach((orderLineId, featuresToUpdate) -> {
                    if (featuresToUpdate != null) {
                        UpdateFeaturesRequest request = new UpdateFeaturesRequest();
                        request.setId(orderLineId);
                        request.setFeatures(JSON.toJSONString(featuresToUpdate));
                        Map<String,Integer> subOrderVersionMap = updateFeaturesReq.getSubOrderVersionMap();
                        if(subOrderVersionMap != null){
                            request.setSyncVersion(subOrderVersionMap.get(orderLineId));
                        }
                        com.epoch.app.crb2btradecenter.domain.orderline.dto.UpdateFeaturesResponse aLong = this.orderLineService.updateFeatures(request);
                        if (aLong.getCount() <= 0L) {
                            log.error("OrderLineWriteRepositoryImpl#updateFeatures_fail");
                            throw new RepositoryException("OTS-05-001-10-16-033");
                        }
                    }
                });
            }

        } else {
            throw new RepositoryException("OTS-05-001-10-16-034");
        }


        return true;
    }

    @RepositoryInvoker
    private  OrderLine createOrderLineConverter(OrderLineSDO orderLineSDO) {
        OrderLine orderLine = new OrderLine();
        boolean isNewOrderLine =false;
        if (StringUtils.isNotBlank(orderLineSDO.getId())) {
            orderLine.setId(Long.parseLong(orderLineSDO.getId()));
        }else{
            isNewOrderLine =true;
        }
        if (Objects.nonNull(orderLineSDO.getScItemSDO())) {
            orderLine.setScItemOutCode(orderLineSDO.getScItemSDO().getScItemOutCode());
            orderLine.setProductationTime(orderLineSDO.getScItemSDO().getProductationTime());
        }
        if(StringUtils.isNotBlank(orderLineSDO.getConfirmQuantity())){
            orderLine.setConfirmQuantity(Double.valueOf(orderLineSDO.getConfirmQuantity()).intValue());
        }
        orderLine.setClosed(orderLineSDO.getClosed());
        orderLine.setMainOrderBizId(orderLineSDO.getMainOrderBizId());
        orderLine.setSerialNumber(orderLineSDO.getSerialNumber());
        orderLine.setSourceLineNum(orderLineSDO.getSourceLineNum());
        orderLine.setFrontLineNum(orderLineSDO.getFrontLineNum());
        orderLine.setMainOrderId(orderLineSDO.getMainOrderId());
        orderLine.setOrderLineTag(orderLineSDO.getOrderLineTag());
        orderLine.setBizCode(orderLineSDO.getBizCode());
        orderLine.setOuterOrderLineId(orderLineSDO.getOuterOrderLineId());
        orderLine.setCustomerCode(orderLineSDO.getCustomerCode());
        orderLine.setSubStatus(orderLineSDO.getSubStatus());
        orderLine.setGiftQuantity(orderLineSDO.getGiftQuantity());
        orderLine.setTaxRate(orderLineSDO.getTaxRate());
        // 取消状态的订单行不能改成已完成状态，防止把业中订单的状态刷掉
        log.info("OrderWriteEntity.createOrderLineConverter orderLineSDO={}", JSON.toJSONString(orderLineSDO));
        if (StringUtils.isNotBlank(orderLineSDO.getRefuseReasonCode()) && !OrderStatus.CANCELLED.getCode().equals(orderLineSDO.getStatus())) {
            log.info("OrderWriteEntity.createOrderLineConverter setStatus={}", OrderStatus.COMPLETED.getCode());
            orderLine.setStatus(OrderStatus.COMPLETED.getCode());
        }else{
            orderLine.setStatus(orderLineSDO.getStatus());
            log.info("OrderWriteEntity.createOrderLineConverter orderLineSDO={}", JSON.toJSONString(orderLineSDO));
        }
        orderLine.setPayStatus(orderLineSDO.getPayStatus());
        orderLine.setPayTime(orderLineSDO.getPayTime());
        ScItemSDO scItemSDO = orderLineSDO.getScItemSDO();
        if (scItemSDO != null) {
            orderLine.setCategoryCode(scItemSDO.getCategoryCode());
            orderLine.setCategoryDesc(scItemSDO.getCategoryDesc());
            orderLine.setCategoryChildCode(scItemSDO.getCategoryChildCode());
            orderLine.setCategoryChildDesc(scItemSDO.getCategoryChildDesc());

            orderLine.setFirstCategoryCode(scItemSDO.getFirstCategoryCode());
            orderLine.setFirstCategoryDesc(scItemSDO.getFirstCategoryDesc());
            orderLine.setSecondCategoryCode(scItemSDO.getSecondCategoryCode());
            orderLine.setSecondCategoryDesc(scItemSDO.getSecondCategoryDesc());
            orderLine.setSaleUnit(scItemSDO.getSaleUnit());
            orderLine.setSaleUnitName(scItemSDO.getSaleUnitName());
            orderLine.setInventoryUnitCode(scItemSDO.getInventoryUnitCode());
            orderLine.setInventoryUnit(scItemSDO.getInventoryUnitName());
            orderLine.setUnitConvert(scItemSDO.getUnitConvert());
            orderLine.setUnitPrice(scItemSDO.getUnitPrice() == null ? null :scItemSDO.getUnitPrice().toString());
            orderLine.setQuantity(scItemSDO.getQuantity());
            orderLine.setActivityPrice(scItemSDO.getActivityPrice() == null ? null :scItemSDO.getActivityPrice().toString());
            orderLine.setScItemId(scItemSDO.getScItemId());
            orderLine.setScItemTitle(scItemSDO.getScItemTitle());
            orderLine.setProductBarCode(scItemSDO.getItemBarCode());
            orderLine.setProductGroupCode(scItemSDO.getProductGroupCode());
            orderLine.setProductGroupName(scItemSDO.getProductGroupName());
            orderLine.setProductationTime(scItemSDO.getProductationTime());
            // 一盘货新增入参
            if (Objects.nonNull(scItemSDO.getActivityPrice())) {
                orderLine.setTotalActivityFee(String.valueOf(scItemSDO.getActivityPrice() * scItemSDO.getQuantity()));
            }
            orderLine.setInnerProductCode(scItemSDO.getInnerProductCode());
            orderLine.setInnerProductName(scItemSDO.getInnerProductName());
        }
        // 一盘货新增入参
        if (Objects.nonNull(orderLineSDO.getTotalActivityFee())) {
            orderLine.setTotalActivityFee(orderLineSDO.getTotalActivityFee());
        }
        orderLine.setTotalActivityFee(null == orderLineSDO.getShouldPayFee() ? null : orderLineSDO.getShouldPayFee().toString());
        orderLine.setShouldPayFee(null == orderLineSDO.getShouldPayFee() ? null : orderLineSDO.getShouldPayFee().toString());
        orderLine.setActualPaidFee(null == orderLineSDO.getActualPaidFee() ? null : orderLineSDO.getActualPaidFee().toString());
        orderLine.setDeliveryStatus(orderLineSDO.getDeliveryStatus());
        orderLine.setDeliveryTime(orderLineSDO.getDeliveryTime());
        orderLine.setEndTime(orderLineSDO.getEndTime());
        orderLine.setActivityCode(orderLineSDO.getActivityCode());
        orderLine.setActivityName(orderLineSDO.getActivityName());
        orderLine.setFrontOrderLineId(orderLineSDO.getFrontOrderLineId());
        orderLine.setRemark(orderLineSDO.getRemark());
        orderLine.setSyncVersion(orderLineSDO.getSyncVersion());

        orderLine.setRefuseReasonName(orderLineSDO.getRefuseReasonName());
        orderLine.setRefuseReasonCode(orderLineSDO.getRefuseReasonCode());
        orderLine.setDeliveryAmount(orderLineSDO.getDeliveryAmount());
        orderLine.setGmtCreate(orderLineSDO.getGmtCreate());
        orderLine.setGmtModified(orderLineSDO.getGmtModified() == null? new Date() : orderLineSDO.getGmtModified());
        orderLine.setCreatorId(orderLineSDO.getCreatorId());
        orderLine.setCreatorName(orderLineSDO.getCreatorName());
        orderLine.setModifierId(orderLineSDO.getModifierId());
        orderLine.setModifierName(orderLineSDO.getModifierName());
        orderLine.setReturnCharacter(orderLineSDO.getReturnCharacter());
        orderLine.setOrderLineTag(orderLineSDO.getOrderLineTag());

        orderLine.setCumulativeReceiptQuantity(orderLineSDO.getCumulativeReceiptQuantity());
        orderLine.setCumulativeProcessingQuantity(orderLineSDO.getCumulativeProcessingQuantity());
        orderLine.setManualPrice(orderLineSDO.getManualPrice());
        orderLine.setManualTotalAmount(orderLineSDO.getManualTotalAmount());
        orderLine.setSourceLineNum(orderLineSDO.getSourceLineNum());
        orderLine.setStockConversionNum(orderLineSDO.getStockConversionNum());
        orderLine.setCumulativeWaitOutboundQuantity(orderLineSDO.getCumulativeWaitOutboundQuantity());
        orderLine.setCumulativeReceivedQuantity(orderLineSDO.getCumulativeReceivedQuantity());
        orderLine.setCumulativeNoticeQuantity(orderLineSDO.getCumulativeNoticeQuantity());

        boolean isOrderCenterOrder = false;
        Map<String, String> features = orderLineSDO.getFeatures();
        if (MapUtils.isNotEmpty(features)) {
            if (!features.containsKey("giftFlag")){
              features.put("giftFlag","X");
            }
            String featureStr = JSONObject.toJSONString(features);
            orderLine.setFeatures(featureStr);

            if ("OrderCenter".equals(features.get("os"))) {
                isOrderCenterOrder = true;
            }
        }else {
            features=new HashMap<>();
            features.put("giftFlag","X");
            String featureStr = JSONObject.toJSONString(features);
            orderLine.setFeatures(featureStr);
        }
        orderLine.setBizFeatures(orderLineSDO.getBizFeatures());

        if (!isOrderCenterOrder || isNewOrderLine) {
            // 非业中订单更新仓库信息，防止业中订单的仓库信息被改成相同的值
            orderLine.setShippingWarehouseCode(orderLineSDO.getShippingWarehouseCode());
            orderLine.setShippingWarehouseName(orderLineSDO.getShippingWarehouseName());
            orderLine.setShippingWarehouseOutCode(orderLineSDO.getShippingWarehouseOutCode());
            orderLine.setStockCode(orderLineSDO.getStockCode());
            orderLine.setDeliveryFactoryCode(orderLineSDO.getDeliveryFactoryCode());
            orderLine.setReceiveWarehouseCode(orderLineSDO.getReceiveWarehouseCode());
            orderLine.setReceiveWarehouseOutCode(orderLineSDO.getReceiveWarehouseOutCode());
            orderLine.setReceiveWarehouseName(orderLineSDO.getReceiveWarehouseName());
            orderLine.setReceiveStockCode(orderLineSDO.getReceiveStockCode());
            orderLine.setReceiveFactoryCode(orderLineSDO.getReceiveFactoryCode());
        }

        return orderLine;
    }

    @Override
    public UpdateCumulativeNoticeQuantityAndFeaturesResponse updateCumulativeNoticeQuantityAndFeatures(UpdateCumulativeNoticeQuantityAndFeaturesRequest updateCumulativeNoticeQuantityAndFeaturesRequest) {
        return orderLineService.updateCumulativeNoticeQuantityAndFeatures(updateCumulativeNoticeQuantityAndFeaturesRequest);
    }
}
